package net.mihome.app.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.Letter;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.UIHelper;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import me.maxwin.view.XListView;

/**
 * Created by ZHAO on 2015/2/1 0001.
 */
public class BigpaperLetterActivity extends  BaseActivity {
    XListView letterXlist;
    List<Letter> letters=new ArrayList<>();
    LetterAdapter letterAdapter;
    View clearAll;
    int begin=0;
    int num=10;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bigpaper_letter_list);
        letterXlist= (XListView) findViewById(R.id.bigpaper_letter_list_view);
        letterAdapter=new LetterAdapter(this,letters);
        letterXlist.setAdapter(letterAdapter);
        letterXlist.setPullLoadEnable(true);
        letterXlist.setPullRefreshEnable(true);
        letterXlist.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                initData(false);
            }

            @Override
            public void onLoadMore() {
                initData(true);
            }
        });
        letterXlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (view != null) {
                    LetterAdapter.ViewClass viewClass = (LetterAdapter.ViewClass) view.getTag();
                    if (viewClass != null && viewClass.letter != null) {
                        Letter letter = viewClass.letter;
                        if (letter.getBigpaperId() != null) {
                            UIHelper.showTweetDetail(BigpaperLetterActivity.this, letter.getBigpaperId());
                        } else {
                            Toast.makeText(BigpaperLetterActivity.this, "消息已经失效", Toast.LENGTH_SHORT).show();
                        }
                        update(letter);
                    }
                }
            }
        });
        clearAll=findViewById(R.id.container_remove);
        clearAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AppContext.ASYNC_HTTP_CLIENT.get(BigpaperLetterActivity.this,URLs.MIHOME_GET_BIGPAPER_CLEAR_ALL,new MiAsyncHttpResponseHandler<Map>() {
                    @Override
                    public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                        Toast.makeText(BigpaperLetterActivity.this,"清除完毕",Toast.LENGTH_SHORT).show();
                        letterXlist.startRefresh();
                    }

                    @Override
                    public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                        Toast.makeText(BigpaperLetterActivity.this,"清除失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        initData(false);
    }
    public void initData(final boolean isMore){
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        if(isMore){
            begin=(begin+1)*num;
        }else{
            begin=0;
        }
        requestParams.add("begin",begin+"");
        requestParams.add("num",num+"");
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_GET_BIGPAPER_LETTER_LIST,requestParams, new MiAsyncHttpResponseHandler<List<Map>>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<List<Map>> responsePojo) {
                List<Letter> letters1=Letter.parseList(responsePojo.getData());
                if(letters1!=null&&!letters1.isEmpty()){
                    if(!isMore){
                        letters.clear();
                        letters.addAll(letters1);
                    }else{
                        letters.addAll(letters1);
                    }
                    letterAdapter.notifyDataSetChanged();
                }else{
                    if(begin==0&&num>0){
                        letters.clear();
                    }
                }
                letterXlist.stopRefresh();
                letterXlist.stopLoadMore();
                letterXlist.setRefreshTime("不久前");
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(BigpaperLetterActivity.this, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();
                letterXlist.stopRefresh();
                letterXlist.stopLoadMore();
                letterXlist.setRefreshTime("不久前");
            }
        });
    }
    /**
     * 将一个已读的系统消息置为已读状态
     * */
    public void update(final Letter letter){
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.add("id",letter.getId()+"");
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_GET_BIGPAPER_LETTER_UPDATE,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                Iterator<Letter> iterator=letters.iterator();
                while(iterator.hasNext()){
                    Letter letter1=iterator.next();
                    if(letter==letter1){
                        iterator.remove();
                    }
                }
                letterAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {

            }
        });
    }
    public void back(View view){
        BigpaperLetterActivity.this.finish();
    }
 }

class LetterAdapter extends BaseAdapter {

    private List<Letter> letterList=new ArrayList<>();
    private Context context;
    private LayoutInflater listContainer;// 视图容器
    public LetterAdapter(Context context,List<Letter> letterList){
        this.context=context;
        this.letterList=letterList;
        this.listContainer = LayoutInflater.from(context); // 创建视图容器并设置上下文
    }
    public static class ViewClass{
        ImageView avatarIv;
        TextView timeTv;
        Letter letter;
        TextView fromNameTv;
        TextView fromContentTv;
        TextView yuanewnTv;
    }
    @Override
    public int getCount() {
        return letterList.size();
    }

    @Override
    public Object getItem(int i) {
        return letterList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return letterList.get(i).getId();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewClass viewClass= null;
        if(view==null||view.getTag()==null){
            viewClass=new ViewClass();
            view = listContainer.inflate(R.layout.bigpaper_letter_listitem, null);
            viewClass.avatarIv= (ImageView) view.findViewById(R.id.letter_avatar);
            viewClass.timeTv= (TextView) view.findViewById(R.id.letter_time);
            viewClass.fromNameTv= (TextView) view.findViewById(R.id.letter_from_name);
            viewClass.fromContentTv= (TextView) view.findViewById(R.id.letter_content);
            viewClass.yuanewnTv= (TextView) view.findViewById(R.id.yuanwen_content);

            view.setTag(viewClass);
        }else{
            viewClass= (ViewClass) view.getTag();
        }
        Letter letter=letterList.get(i);
        if(letter.getUser()!=null&&letter.getUser().getFace()!=null){
            ImageLoader.getInstance().displayImage(letter.getUser().getFace(),viewClass.avatarIv);
        }else{
            viewClass.avatarIv.setImageResource(R.drawable.default_face);
        }
        if(letter.getUser()!=null){
            if(letter.getUser().getMarkName()!=null&&!"".equals(letter.getUser().getMarkName())){
                viewClass.fromNameTv.setText(letter.getUser().getMarkName());
            }else{
                viewClass.fromNameTv.setText(letter.getUser().getName());
            }
        }else{
            viewClass.fromNameTv.setText(letter.getSendUid());
        }
        if(letter.getTweet()!=null){
            viewClass.yuanewnTv.setText(letter.getTweet().getBody());
        }
        if(letter.getComment()!=null){
            viewClass.fromContentTv.setText(letter.getComment().getBody());
        }else{
            viewClass.fromContentTv.setText("评论了您的大字报");
        }
        viewClass.timeTv.setText(letter.getCreateAt());
        viewClass.letter=letter;
        return view;
    }
}
